package com.ttt.utils;

import com.alibaba.druid.pool.DruidDataSourceFactory;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DbConnectionUtil {
    // 创建 Druid 数据源
    private static DataSource dataSource;

    static {
        // 初始化连接池
        Properties properties = new Properties();
        properties.setProperty("url", "jdbc:mysql://101.132.85.231:3308/db");
        properties.setProperty("username", "root");
        properties.setProperty("password", "123456");
        properties.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");


        try {
            dataSource = DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    // 获取数据库连接
    public  Connection getConnection() throws SQLException {
        return dataSource.getConnection();
    }

    // 获取 PreparedStatement
    public  PreparedStatement getPreparedStatement(String sql) throws SQLException {
        return getConnection().prepareStatement(sql);
    }

    // 获取 Statement
    public  Statement getStatement() throws SQLException {
        return getConnection().createStatement();
    }

    // 关闭资源
    public  void close(ResultSet rs, Statement stmt, Connection conn) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (stmt != null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }

    public  void main(String[] args) {
        try {
            // 获取连接
            Connection connection = getConnection();
            // 获取 PreparedStatement
            PreparedStatement preparedStatement = getPreparedStatement("SELECT * FROM your_table WHERE id = ?");
            preparedStatement.setInt(1, 1);

            ResultSet resultSet = preparedStatement.executeQuery();

            while (resultSet.next()) {
                // 处理结果集
                System.out.println(resultSet.getString("column_name"));
            }

            // 关闭资源
            close(resultSet, preparedStatement, connection);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}